package com.example.ayniu.treadmill;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.ayniu.treadmill.adapter.MyPagerAdapter;
import com.example.ayniu.treadmill.base.blueInterface;
import com.example.ayniu.treadmill.bean.ClassBean;
import com.example.ayniu.treadmill.bluetooth.BluetoothChatService;
import com.example.ayniu.treadmill.bluetooth.BluetoothController;
import com.example.ayniu.treadmill.bluetooth.DeviceListActivity;
import com.example.ayniu.treadmill.fragment.Fragment_class;
import com.example.ayniu.treadmill.fragment.Fragment_main;
import com.example.ayniu.treadmill.util.MyViewPager;
import com.example.ayniu.treadmill.util.UserInfoUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

/*
*   使用volley框架进行网络通信
*   By zxk
* */

public class MainActivity extends FragmentActivity implements RadioGroup.OnCheckedChangeListener,
        MyViewPager.OnPageChangeListener {

    //增加首页滑动效果(A)170312
    //几个代表页面的常量
    public static final int PAGE_ONE = 0;
    public static final int PAGE_TWO = 1;
    public static final int PAGE_THREE = 2;

    public MyPagerAdapter mypagerAdapter;
    public MyViewPager mViewpager;
    private RadioGroup mRadiogroup;
    private RadioButton rbt_main,rbt_class,rbt_set;

    public static Activity mainInstance;//用于在其他Activity使用Main中的方法

    //计算Toast的出现时间
    private long firstTimeOfToast;
/*蓝牙*/
    private Button bt_btconnect;
    public static RelativeLayout layout_bluetooth;
// 蓝牙发送的message消息类型
    //Intent request
    protected static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    protected static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
    protected static final int REQUEST_ENABLE_BT = 3;

    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
    // Name of the connected device
    private String mConnectedDeviceName = null;
    // String buffer for outgoing messages
    protected static StringBuffer mOutStringBuffer;
    // Local Bluetooth adapter
    protected static BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the chat services
    public static BluetoothChatService mChatService = null;

/*网络通信*/
    public RequestQueue mQueue;         //http请求队列对象
    //用户验证 和课程请求
    private String LOGIN_CLASSREQUEST_URL = "http://www.fescale.com/product/hiha/hiha0.php/";

    public List<ClassBean> list_ClassBean = new LinkedList<ClassBean>();

    //private Button btclass_refresh;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 透明状态栏,实现沉浸式页面效果
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        mainInstance = this;

        initView();
/*蓝牙*/
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "手机蓝牙不可用", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        rbt_main.setChecked(true);//设置RadioGroup的默认选择
        rbt_main.setBackgroundResource(R.drawable.bg_rbt);

/* 网络通信 */
        mQueue = Volley.newRequestQueue(this);//初始化http请求队列对象

        httpLoginAndGetClasses();//验证登录，获取用户课程

    }

    private void initView() {

        layout_bluetooth = (RelativeLayout) findViewById(R.id.layout_bluetoothconnect);
        bt_btconnect = (Button)findViewById(R.id.bt_btconnect);
        bt_btconnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent serverIntent = new Intent(MainActivity.this, DeviceListActivity.class);
                startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
            }
        });
        mRadiogroup = (RadioGroup)findViewById(R.id.radiogroup);
        rbt_main = (RadioButton)findViewById(R.id.rbt_main);
        rbt_class = (RadioButton)findViewById(R.id.rbt_class);
        rbt_set = (RadioButton)findViewById(R.id.rbt_set);
        mRadiogroup.setOnCheckedChangeListener(this);

        mypagerAdapter = new MyPagerAdapter(getSupportFragmentManager());

        mViewpager = (MyViewPager) findViewById(R.id.viewpager);
        mViewpager.setAdapter(mypagerAdapter);
        mViewpager.setCurrentItem(0);
        mViewpager.addOnPageChangeListener(this);

        //btclass_refresh = (Button) findViewById(R.id.btclass_refresh);
    }

    //设置RadioGroup点击事件处理
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        Log.i("xk", "onCheckedChanged: "+Fragment_main.MAIN_STATUS+"/"+Fragment_main.MAIN_STATUS_START);
        if(Fragment_main.MAIN_STATUS == Fragment_main.MAIN_STATUS_START){
        switch (checkedId) {
            case R.id.rbt_main:
                rbt_main.setBackgroundResource(R.drawable.bg_rbt);
                rbt_main.setTextColor(getResources().getColor(R.color.main));
                rbt_class.setBackgroundResource(R.color.main);
                rbt_class.setTextColor(getResources().getColor(R.color.white));
                rbt_set.setBackgroundResource(R.color.main);
                rbt_set.setTextColor(getResources().getColor(R.color.white));
                mViewpager.setCurrentItem(PAGE_ONE);
                break;
            case R.id.rbt_class:
                rbt_main.setBackgroundResource(R.color.main);
                rbt_main.setTextColor(getResources().getColor(R.color.white));
                rbt_class.setBackgroundResource(R.drawable.bg_rbt);
                rbt_class.setTextColor(getResources().getColor(R.color.main));
                rbt_set.setBackgroundResource(R.color.main);
                rbt_set.setTextColor(getResources().getColor(R.color.white));
                mViewpager.setCurrentItem(PAGE_TWO);
                break;
            case R.id.rbt_set:
                rbt_main.setBackgroundResource(R.color.main);
                rbt_main.setTextColor(getResources().getColor(R.color.white));
                rbt_class.setBackgroundResource(R.color.main);
                rbt_class.setTextColor(getResources().getColor(R.color.white));
                rbt_set.setBackgroundResource(R.drawable.bg_rbt);
                rbt_set.setTextColor(getResources().getColor(R.color.main));
                mViewpager.setCurrentItem(PAGE_THREE);
                break;
            default:
                break;
        }
        }else{
            showToast("正在进行常规训练，结束后才可切换");
        }
    }

    //重写ViewPager页面切换的处理方法
    @Override
    public void onPageScrollStateChanged(int state) {
        if(Fragment_main.MAIN_STATUS == Fragment_main.MAIN_STATUS_START){
        //state的状态有三个，0表示什么都没做，1正在滑动，2滑动完毕
        if (state == 2) {
            switch (mViewpager.getCurrentItem()) {
                case PAGE_ONE:
                    rbt_main.setBackgroundResource(R.drawable.bg_rbt);
                    rbt_main.setTextColor(getResources().getColor(R.color.main));
                    rbt_class.setBackgroundResource(R.color.main);
                    rbt_class.setTextColor(getResources().getColor(R.color.white));
                    rbt_set.setBackgroundResource(R.color.main);
                    rbt_set.setTextColor(getResources().getColor(R.color.white));
                    rbt_main.setChecked(true);
                    break;
                case PAGE_TWO:
                    rbt_main.setBackgroundResource(R.color.main);
                    rbt_main.setTextColor(getResources().getColor(R.color.white));
                    rbt_class.setBackgroundResource(R.drawable.bg_rbt);
                    rbt_class.setTextColor(getResources().getColor(R.color.main));
                    rbt_set.setBackgroundResource(R.color.main);
                    rbt_set.setTextColor(getResources().getColor(R.color.white));
                    rbt_class.setChecked(true);
                    break;
                case PAGE_THREE:
                    rbt_main.setBackgroundResource(R.color.main);
                    rbt_main.setTextColor(getResources().getColor(R.color.white));
                    rbt_class.setBackgroundResource(R.color.main);
                    rbt_class.setTextColor(getResources().getColor(R.color.white));
                    rbt_set.setBackgroundResource(R.drawable.bg_rbt);
                    rbt_set.setTextColor(getResources().getColor(R.color.main));
                    rbt_set.setChecked(true);
                    break;
                default:
                    break;
            }
        }
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    /**
     * 以下为蓝牙实现
     */
/*蓝牙*/
    @Override
    public void onStart() {
        super.onStart();
        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {

            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
            if (mChatService == null)
                setupChat();
        }
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
                // Start the Bluetooth chat services
                mChatService.start();
                FirstConnectDevice(true);//进行自动连接尝试
            }
        }
    }

    private void setupChat() {

        // Initialize the BluetoothChatService to perform bluetooth connections
        mChatService = new BluetoothChatService(this, mHandler);

        // Initialize the buffer for outgoing messages
        mOutStringBuffer = new StringBuffer("");
    }

    @Override
    public synchronized void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mBluetoothAdapter.disable();
        // Stop the Bluetooth chat services
        if (mChatService != null) mChatService.stop();
    }

    /**
     * 发送数据到设备的方法
     * @param message  A string of text to send.
     */
    public void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }

        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            byte[] send = message.getBytes();
            mChatService.write(send);

            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
            Log.i("sendMessage", "send: "+message);
        }
    }

    /**
     * 发送数据到设备的方法
     * @param message  A string of text to send.
     */
    public void sendMessage(byte[] message, int length) {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }

        // Check that there's actually something to send
        if (length > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            mChatService.write(message);
            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
            Log.i("sendMessage", "send: " + message);

            String h = "";
            for(int i = 0; i < length; i++){
                String temp = Integer.toHexString(message[i] & 0xFF);
                if(temp.length() == 1){
                    temp = "0" + temp;
                }
                h = h + " "+ temp;
            }
            Log.i("sendMessage", "send: " + h);
        }
    }

    private final void setStatus(int resId) {
        final ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setSubtitle(resId);
        }
    }

    private final void setStatus(CharSequence subTitle) {
        final ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setSubtitle(subTitle);
        }
    }

    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BluetoothController.MESSAGE_STATE_CHANGE:
                    Log.i("MESSAGE_STATE_CHANGE", "CHANGE: " + msg.arg1);
                    switch (msg.arg1) {
                        case BluetoothChatService.STATE_CONNECTED:
                            setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
                            //showToast(getString(R.string.title_connected_to));
                            layout_bluetooth.setVisibility(View.GONE);
                            handShake();//发送握手请求
                            mViewpager.setVisibility(View.VISIBLE);
                            break;
                        case BluetoothChatService.STATE_CONNECTING:
                            setStatus(R.string.subtitle_connecting);
                            showToast(getString(R.string.subtitle_connecting));
                            break;
                        case BluetoothChatService.STATE_LISTEN:
                        case BluetoothChatService.STATE_NONE:
                            setStatus(R.string.not_connected);
                            layout_bluetooth.setVisibility(View.VISIBLE);
                            mViewpager.setVisibility(View.GONE);
                            break;
                    }
                    break;
                case BluetoothController.MESSAGE_WRITE:
                    byte[] writeBuf = (byte[]) msg.obj;
                    // construct a string from the buffer
                    String writeMessage = new String(writeBuf);
                    //showToast("发送："+writeMessage);
                    break;
                case BluetoothController.MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;
                    // construct a string from the valid bytes in the buffer
                    String readMessage = new String(readBuf, 0, msg.arg1);
                    //showToast("设备回复：" + msg.arg1 + "=" + readMessage);
                    //Log.i("xk", "handleMessage: "+readMessage);

                    blueInterface blueI = new blueInterface();
                    if(msg.arg2 == blueI.OAM_APP_HANDSHAKE_CFM) {
                        //握手响应数据待使用(A)
                        blueInterface.handShakeCfm handShakeCfm = blueI.new handShakeCfm();
                        handShakeCfm.decodeFrame(readBuf);
                        //showToast("已握手" + handShakeCfm.deviceId);
                        Log.i("test", "readMessage(握手回复): " + handShakeCfm.deviceId + handShakeCfm.version);
                        // 连接成功后发送一条 查询状态的指令 getpara 用于查看设备是否在运行
                    }
                    else if(msg.arg2 == blueI.OAM_APP_START_CFM) {
                        blueInterface.startCfm startCfm = blueI.new startCfm();
                        startCfm.decodeFrame(readBuf);
                        //showToast("已开始" + startCfm.usResult);
                        Log.i("test", "start(开始回复):result:" + startCfm.usResult);
                    }
                    else if(msg.arg2 == blueI.OAM_APP_STOP_CFM) {
                        blueInterface.stopCfm stopCfm = blueI.new stopCfm();
                        stopCfm.decodeFrame(readBuf);
                        //showToast("已停止" + stopCfm.usResult);
                        Log.i("test", "readMessage(停止回复): " + stopCfm.usResult);
                    }
                    else if(msg.arg2 == blueI.OAM_APP_PARA_GET_CFM) {
                        blueInterface.paraGetCfm paraGetCfm = blueI.new paraGetCfm();
                        paraGetCfm.decodeFrame(readBuf);
                        if(paraGetCfm.status == 2 && true) // 如果现在是课程模式，并且课程已经停止，通知关闭课程页面
                        {
                            ;//
                        }
                        // 第一次获取para
                        if((paraGetCfm.status == 1 || paraGetCfm.status == 2) && paraGetCfm.workType == 0 && true)
                        {
                            ;//切换到自由模式运动界面
                        }
                        if((paraGetCfm.status == 1 || paraGetCfm.status == 2) && paraGetCfm.workType == 2 && true)
                        {
                            ;//切换到课程模式运动界面
                        }
                        UserInfoUtil.thisSpeed = (int)(paraGetCfm.speed);

                        String tempStr;
                        tempStr = String.valueOf(paraGetCfm.distance % 1000);
                        if(tempStr.length() == 2) {
                            tempStr = "0" + tempStr;
                        }
                        else if(tempStr.length() == 1) {
                            tempStr = "00" + tempStr;
                        }
                        String showDistanceStr = String.valueOf(paraGetCfm.distance / 1000) + "." + tempStr;

                        tempStr = String.valueOf(paraGetCfm.runTime % 60);
                        if(tempStr.length() < 2) {
                            tempStr = "0" + tempStr;
                        }
                        String showRunTimeStr = String.valueOf(paraGetCfm.runTime / 60) + ":" + tempStr;

                        tempStr = String.valueOf(paraGetCfm.speed % 10);
                        if(tempStr.length() < 1) {
                            tempStr = "0" + tempStr;
                        }
                        String showSpeedStr = String.valueOf(paraGetCfm.speed / 10) + "." + tempStr;
                        if(isClassActivityTop()){
                            //更新课程模式界面文本参数(A)
                            Log.i("xkread", "classdataChange");
                            ClassActivity.class_data_distance.setText(showDistanceStr);
                            ClassActivity.class_data_calories.setText(String.valueOf(paraGetCfm.calorie));
                            ClassActivity.class_data_time.setText(showRunTimeStr);
                            ClassActivity.class_data_speed.setText(showSpeedStr);
                        } else {
                            //更新自由模式界面文本参数(A)
                            Fragment_main.main_data_distance.setText(showDistanceStr);
                            Fragment_main.main_data_calories.setText(String.valueOf(paraGetCfm.calorie));
                            Fragment_main.main_data_time.setText(showRunTimeStr);
                            Fragment_main.main_data_speed.setText(showSpeedStr);
                        }
                        Log.i("xk", "para:status:" + paraGetCfm.status + " distance:" + paraGetCfm.distance + " calorie:" +
                                paraGetCfm.calorie + " runtime:" + paraGetCfm.runTime + " speedlev:" + paraGetCfm.speedLevel);
                    }
                    else if(msg.arg2 == blueI.OAM_APP_SPEED_CFM) {
                        blueInterface.speedCfm speedCfm = blueI.new speedCfm();
                        speedCfm.decodeFrame(readBuf);
                        //showToast("已速度" + speedCfm.speedLev);

                        UserInfoUtil.thisSpeed = (int)(speedCfm.speedLev);
                        String tempStr = String.valueOf(speedCfm.speedLev % 10);
                        if(tempStr.length() < 1) {
                            tempStr = "0" + tempStr;
                        }
                        String showSpeedStr = String.valueOf(speedCfm.speedLev / 10) + "." + tempStr;
                        Fragment_main.main_data_speed.setText(showSpeedStr);

                        Log.i("Test","readMessage(速度回复):" + speedCfm.speedLev);
                    }
                    else {
                        Log.e("xk", "msg is error: " + msg.arg2);
                    }
                    break;
                case BluetoothController.MESSAGE_DEVICE_NAME:
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                    break;
                case BluetoothController.MESSAGE_TOAST:
                    Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                            Toast.LENGTH_SHORT).show();
                    if(msg.getData().getString(TOAST).equals("设备连接断开！")) {
                        layout_bluetooth.setVisibility(View.VISIBLE);
                        mViewpager.setVisibility(View.GONE);
                    }else if(msg.getData().getString(TOAST).equals("无法连接设备"))
                        bt_btconnect.setText(getString(R.string.bt_manualconnect));
                    break;
            }
        }
    };

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE_SECURE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    connectDevice(data, true);
                }
                break;
            case REQUEST_CONNECT_DEVICE_INSECURE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    connectDevice(data, false);
                }
                break;
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    // Bluetooth is now enabled, so set up a chat session
                    setupChat();
                } else {
                    // User did not enable Bluetooth or an error occurred
                    Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                    finish();
                }
        }
    }

    private void connectDevice(Intent data, boolean secure) {
        // Get the device MAC address
        String address = data.getExtras()
                .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        // Get the BluetoothDevice object
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        // Attempt to connect to the device
        mChatService.connect(device, secure);
    }

    /*开启app后，与默认设备自动连接*/
    private void FirstConnectDevice(boolean secure){
        //获取已配对的蓝牙设备
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        // If there are paired devices, add each one to the ArrayAdapter
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                //根据名称进行默认自动连接
                if(device.getName().equals("HC-06")){
                    String address = device.getAddress();
                    Log.i("getAddress", address);
                    // Get the BluetoothDevice object
                    BluetoothDevice first_device = mBluetoothAdapter.getRemoteDevice(address);
                    // Attempt to connect to the device
                    mChatService.connect(first_device, secure);
                }
            }
        }
    }

    /*向设备发送握手请求*/
    public void handShake(){
        blueInterface blueI = new blueInterface();
        blueInterface.handShakeReq handShakeReq = blueI.new handShakeReq();
        String str_type = "0-pluss";
        handShakeReq.msgType = 0;
        //handShakeReq.usRes = 0;
        byte[] sendData = new byte[512];
        int sendLength = handShakeReq.createFrame(sendData);
        byte[] realSend = new byte[sendLength];
        sendLength = handShakeReq.createFrame(realSend);
        sendMessage(realSend, sendLength);
    }

    /*网络通信获取课程信息*/
    private void httpLoginAndGetClasses(){
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(LOGIN_CLASSREQUEST_URL,null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray classes_ja = response.getJSONArray("list");
                    if(classes_ja != null) {
                        for(int i = 0; i < classes_ja.length(); i++){
                            JSONObject class_jo = classes_ja.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                            ClassBean classbean = new ClassBean();
                            classbean.setCourse(class_jo.getString("course"));
                            classbean.setFlag(class_jo.getString("flag"));
                            classbean.setTask(class_jo.getString("task"));
                            classbean.setCourseName(class_jo.getString("courseName"));
                            classbean.setCourseAbout(class_jo.getString("courseAbout"));
                            list_ClassBean.add(classbean);
                        }
                        //Fragment_class.list_courseName = list_ClassBean;
                        //重新创建适配，实现姐ma刷新
                        /*mypagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
                        mViewpager.setAdapter(mypagerAdapter);*/
                        //btclass_refresh.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("JSONException", e.getMessage(), e);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                showToast("网络不可用，请检查网络");
                /*btclass_refresh.setVisibility(View.VISIBLE);
                btclass_refresh.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this,"获取课程信息...",Toast.LENGTH_LONG).show();
                        TimerTask task = new TimerTask(){
                            public void run(){
                                httpLoginAndGetClasses();
                                }
                           };
                        Timer timer = new Timer();
                        timer.schedule(task, 2000);
                    }
                });*/
            }
        });
        mQueue.add(jsonObjectRequest);
    }
    /**
     * 判断ClassActivity是否处于栈顶
     * @return  true在栈顶false不在栈顶
     */
    private boolean isClassActivityTop(){
        Log.i("xkread", "isClassActivityTop");
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        return name.equals(ClassActivity.class.getName());
    }

    public void showToast(String str){
        // Toast的刷新时间为2s
       /* long secondTimeOfToast = System.currentTimeMillis();
        if (secondTimeOfToast - firstTimeOfToast > 2000) {*/
            Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
            /*firstTimeOfToast = secondTimeOfToast;
        }*/
    }
}
